package com.color.admin.log.service.impl;


import com.color.admin.common.core.constant.Constant;
import com.color.admin.common.core.exception.BaseException;
import com.color.admin.common.core.page.PageRequest;
import com.color.admin.common.core.page.PageResponse;
import com.color.admin.common.core.utils.tools.QueryHelp;
import com.color.admin.common.core.utils.web.DateUtils;
import com.color.admin.log.entity.SysLog;
import com.color.admin.log.entity.query.LogCriteria;
import com.color.admin.log.entity.vo.LogSmallVo;
import com.color.admin.log.repository.LogRepository;
import com.color.admin.log.service.LogService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author HaiQiu
 * @date 2022/1/24
 */
@Service
public class LogServiceImpl implements LogService {


    @Autowired
    private LogRepository logRepository;

    @Override
    public void save(SysLog log) {
        SysLog save = logRepository.save(log);
        if (ObjectUtils.isEmpty(save)){
            throw new BaseException(Constant.INSERT_FAIL);
        }
    }

    @Override
    public PageResponse<LogSmallVo> list(PageRequest<LogCriteria> request) {
        LogCriteria criteria = request.getParams();

        Pageable pageable = org.springframework.data.domain.PageRequest.of(request.getNum(),request.getPageSize(),
                Sort.by("createTime").descending());

        Page<SysLog> logs = logRepository.findAll((root, query, criteriaBuilder) ->
                QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<LogSmallVo> logSmallVos = logs.map(log -> {
            LogSmallVo vo = new LogSmallVo();
            BeanUtils.copyProperties(log, vo);
            return vo;
        });

        PageResponse<LogSmallVo> response = new PageResponse<>();
        response.setPageIndex(request.getPageIndex());
        response.setPageSize(request.getPageSize());
        response.setTotalElements(logSmallVos.getTotalElements());
        response.setData(logSmallVos.getContent());
        return response;
    }

    @Override
    public Map<String, Object> lately(String time) {
        Date date = DateUtils.strFormat(time);
        List<Map<String, Object>> mapList = logRepository.lately(date);
        Map<String,Object> map = new HashMap<>(16);
        map.put("row",mapList);
        return map;
    }
}
